package com.iwhalecloud.uncc.domain;
import groovy.lang.Binding;
import groovy.lang.Script;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

@Slf4j
public class ShellScript {
    protected String name;
    protected String script;
    protected boolean isExpression = false;

    /**
     * 脚本动态参数 key<String>=value<Object>
     */
    private Map paraMap = new LinkedHashMap();

    public Map getParaMap() {
        return paraMap;
    }

    public void setParaMap(Map paraMap) {
        this.paraMap = paraMap;
    }

    public void set(Object object) {
        if (object == null || (object instanceof Script) == false) {
            throw new IllegalArgumentException("[scp] is null or not script class!");
        }
        if (this.getScript() == null) {
            return;
        }

        Script scp = (Script) object;

        log.debug("<support>: groovy script=[" + this.getScript() + "]");

        Binding binding = new Binding();
        Set entrys = this.getParaMap().entrySet();
        for (Iterator it = entrys.iterator(); it.hasNext(); ) {
            Map.Entry entry = (Map.Entry) it.next();
            String key = (String) entry.getKey();
            Object value = entry.getValue();
            binding.setProperty(key, value);

            log.debug("<support>: groovy shell para key[" + key + "]=value[" + value + "]");
        }

        scp.setBinding(binding);

    }

    public String getScript() {
        // 当时布尔表达式，且不含有return时
        if (this.isExpression == true && script.indexOf("return ") == -1 && script.indexOf("return\t") == -1) {
            if (!this.script.endsWith(";")) {
                this.script = this.script + ";";
            }
            return "return " + this.script;
        }
        return this.script;
    }

    public void setScript(String script) {
        this.script = script;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isExpression() {
        return isExpression;
    }

    public void setExpression(boolean isExpression) {
        this.isExpression = isExpression;
    }

}
